package com.yuzhenxin.coursesystem.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.framework.common.exception.ServiceException;
import com.example.framework.common.util.ExcelUtils;
import com.yuzhenxin.coursesystem.config.enums.ErrorCodeConstants;
import com.yuzhenxin.coursesystem.controller.admin.vo.UserQueryReqVO;
import com.yuzhenxin.coursesystem.entity.StudentDO;
import com.yuzhenxin.coursesystem.mapper.StudentMapper;
import com.yuzhenxin.coursesystem.service.StudentService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, StudentDO> implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public void insert(StudentDO studentEntity) {
        if (studentMapper.selectById(studentEntity.getId()) != null) {
            //学号已注册过了
            throw ServiceException.of(ErrorCodeConstants.USER_EXISTS);
        }
        studentMapper.insert(studentEntity);
    }

    @Override
    public IPage<StudentDO> selectPage(UserQueryReqVO reqDto) {
        Page<StudentDO> page = new Page<>(reqDto.getPageNo(), reqDto.getPageSize());
        Integer number = reqDto.getNumber();
        String name = reqDto.getName();
        LambdaQueryWrapper<StudentDO> queryWrapper = Wrappers.<StudentDO>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(number), StudentDO::getNumber, number)
                .like(ObjectUtil.isNotEmpty(name), StudentDO::getName, name);
        return studentMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Map<String, String> getStatistic() {
        return studentMapper.getStatistic();
    }

    @Override
    public void exportData(HttpServletResponse response) {
        String fileName = "Student";
        List<StudentDO> studentEntityList = studentMapper.selectList(null);
        ExcelUtils.export(fileName, "Student", studentEntityList, StudentDO.class, response);
    }

}
